const Koa = require('koa')
const app = new Koa()
const config = require("./config/index.json")
// const { logall, logctx, loger } = require('./task/logger.js')


// 获取金蛋理财尊享可投资产品-任务
// require('./task/get_jindan_zunxiang.js')


// 引入 socket 
// require('./socket/index.js')


Date.prototype.format = function(format) {
    var o = {
        "M+": this.getMonth() + 1,
        "d+": this.getDate(),
        "h+": this.getHours(),
        "m+": this.getMinutes(),
        "s+": this.getSeconds(),
        "q+": Math.floor((this.getMonth() + 3) / 3),
        "S": this.getMilliseconds()
    }
    if (/(y+)/.test(format)) {
        format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    }
    for (var k in o) {
        if (new RegExp("(" + k + ")").test(format)) {
            format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
        }
    }
    return format;
}


// 连接数据库
    const db = require('mongoose')

    db.connect(config.mongodb_url, {useNewUrlParser: true})

    db.connection.once('open', () => {
        console.log(new Date().format('yyyy-MM-dd hh:mm:ss'), "数据库连接成功")
    })

    db.connection.on('error', err => {
        console.error(new Date().format('yyyy-MM-dd hh:mm:ss'), '数据库连接错误' + err)
    })

    db.connection.on('disconnected', err => {
        console.log(new Date().format('yyyy-MM-dd hh:mm:ss'), '数据库连接结束' + err)
    })

    global.db = db 


// 引入中间件
const onerror = require('koa-onerror')
const views = require('koa-views')
const bodyparser = require('koa-bodyparser')
const json = require('koa-json')
const jsonp = require('koa-jsonp')
const logger = require('koa-logger')
const cors = require('koa2-cors')

onerror(app) // error handler
app.use(views(__dirname + '/views', {
    extension: 'pug'
}))
app.use(require('koa-static')(__dirname + '/public', { 
    maxage: 1000 * 60 * 60 * 24 // ms 
}))
app.use(async(ctx, next) => { // 全局变量
    ctx.state.G = {
        url: 'http://www.itying.com',
        //userinfo: ctx.session.userinfo,
    }
    await next()
})
app.use(bodyparser({
    enableTypes: ['json', 'form', 'text']
}))
app.use(json())
app.use(jsonp())


// app.use(logger())

// app.use(logall())

app.use(async(ctx, next) => { // logger
    const start = new Date()

    await next()

    if (ctx.request.method == "OPTIONS") {
        ctx.response.status = 200
    }

    let obj = {
        method: ctx.method,
        url: ctx.url,
        query: ctx.query,
        querystring: ctx.querystring,
        message: ctx.message,
        status: ctx.status,
        type: ctx.type,
        length: ctx.length,
        body: ctx.body,
    }
    
    // logctx(obj)
    
    const ms = new Date() - start
    console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
})

app.use(cors({ // 设置跨域访问
    origin: function(ctx) {
        // if (/^\/books/.test(ctx.url)) {
           
        // }
        return '*'
    },
    exposeHeaders: ['application/json', 'charset=utf-8'],
    maxAge: 60,
    credentials: true, // 允许携带cookie，此时origin是服务器域名，而不能是"*"
    allowMethods: ['GET', 'POST', 'PUT', 'DELETE'],
    allowHeaders: ['Content-Type', 'Authorization', 'Accept', 'cjm', 'setcookie'],
}))



 







// 渲染页面文件 render
const index = require('./routes/page/index')
const list = require('./routes/page/list')
const bbs = require('./routes/page/bbs')
const input = require('./routes/page/input')  
const register = require('./routes/page/register')  

app.use(index.routes(), index.allowedMethods()) // 启动路由 + 当请求出错时的处理逻辑
app.use(list.routes(), list.allowedMethods())
app.use(bbs.routes(), bbs.allowedMethods())
app.use(input.routes(), input.allowedMethods()) 
app.use(register.routes(), register.allowedMethods())


// 操作数据库文件 api
const books = require('./routes/api/books')
const test = require('./routes/api/test')
const saveinput = require('./routes/api/saveinput') 
const saveregister = require('./routes/api/register') 

app.use(books.routes(), books.allowedMethods())
app.use(test.routes(), test.allowedMethods())
app.use(saveinput.routes(), saveinput.allowedMethods())
app.use(saveregister.routes(), saveregister.allowedMethods())


// 后台管理文件 admin



// 其他










// 错误处理
app.on('error', (err, ctx) => {
    // loger.error(err)
    console.error('server error', err, ctx)
})

module.exports = app
